(function(angular) {
	'use strict';
	/**
	 * postMessage 数据格式
	{
		interface: evt.data.interface,
		status: 'success', 
		data: data.result
	}
	或
	{
		interface: evt.data.interface,
		status: 'error', 
		data: {
			code: 1,
			message: msg
		}
	}
	 */

	angular
		.module('xianwan')
		.factory('SDK', ['$rootScope', 'Constant', '$injector', 'Meeting',
			function($rootScope, Constant, $injector, Meeting) {
				let self = this;

				const REINIT_TIME_MAX = 5;
				const REINIT_INTERVAL = 500;

				let getReInitTimesMax = function() {
					return REINIT_TIME_MAX;
				};

				let getReInitInterval = function() {
					return REINIT_INTERVAL;
				};

				let successHandler = function(evt, data) {
					evt.source.postMessage({
						interface: evt.data.interface,
						status: 'success', 
						data: data.result
					}, evt.origin);
				};

				let errorHandler = function(evt, msg) {
					evt.source.postMessage({
						interface: evt.data.interface,
						status: 'error', 
						data: {
							code: 1,
							message: msg
						}
					}, evt.origin);
				};

				let postReadyFn = function() {
					window.postMessage({
						from: 'sdk.util.js', 
						isReady: true
					}, Constant.SDK_ORIGIN_URL);
				};

				let sdkInit = function(iframe, app) {

					// let times = 0;
					// times++;
					// if (times > reInitTimesMax) {
					//     throw new Error('初始化 SDK 失败！请重试');
					// }

					// if (sdkInitHandler) {
					//     $timeout.cancel(sdkInitHandler);
					// }

					iframe.addEventListener('message', function(evt) {
						console.log(`sdk.util.js on message:`, evt.data);
					    var evtData = evt.data;
					    var result = {};
						
						if (!evtData.from) {
							return;
						}
					    // if (app.bundles[0].access_endpoints.PC.indexOf(evt.origin) === -1) {
					    //     return false;
					    // }
						
						let interfaceName = evtData.interface;
					    /**
					     * 获取当前用户信息
					     */
					    if (interfaceName.indexOf('getCurrentUserInfo') > -1) {
					    	let User = $injector.get('User');
					    	let Organization = $injector.get('Organization');

					        User.getMyselfDetailInfo()
					            .then(function(data) {
					            	// if (true) {
					            	// 	return Organization.getCurrentOrg();
					            	// }
					            	data.result.employee = Organization.getCurrentOrg();

					                successHandler(evt, data);
					            }, function(msg) {
					                errorHandler(evt, msg);
					            });
					    } 
					    /**
					     * 选择联系人
					     */
					    else if (interfaceName.indexOf('chooseContacts') > -1) {
					        let ChooseContact = $injector.get('ChooseContact');
					        let Modal = $injector.get('Modal');
							
					        ChooseContact.setOptions(evtData.params);
					        Modal.open({
								templateUrl: 'templates/modal/custom_modal_body_temp.html', 
								className: 'modal-discussion',
					            title: '选择联系人',
					            callback: function(selectedItems) {
					                successHandler(evt, {
					                    'result': selectedItems
					                });
					            }
					        });
							$rootScope.$apply();
					    } 
					    /**
					     * 获取用户票据
					     */
					    else if (interfaceName.indexOf('getUserTicket') > -1) {
					    	let Organization = $injector.get('Organization');
					    	let Ticket = $injector.get('Ticket');
					    	let AuthService = $injector.get('AuthService');

					        Organization.findAllOfMyself().then(function(data) {
					            var orgId = data[0].org_code;
					            var currentOrg = Organization.getCurrentOrg();
					            if (!angular.equals(currentOrg, null)) {
					                orgId = currentOrg.org_code;
					            }

					            Ticket.getTicket(AuthService.getToken(), orgId)
					                .then(function(data) {
					                    result = {
					                        'userTicket': data.result.ticket_id
					                    };

					                    successHandler(evt, {
					                        'result': result
					                    });
					                }, function(msg) {
					                    errorHandler(evt, msg);
					                });
					        })
					    } 
					    /**
					     * 打开会话
					     */
					    else if (interfaceName.indexOf('openSession') > -1) {
					        var userId = evtData.params.userId;
					        if (angular.isUndefined(userId)) {
					            errorHandler(evt, '请提供对应的用户标识');
					            return;
					        }
					        $rootScope.hideShadowTransparent();
					        $rootScope.openChatPanel(userId);

					        result = {
					            'message': 'openSessionSuccess'
					        };
					        successHandler(evt, {
					            'result': result
					        });
					    } 
					    /**
					     * 打开链接
					     */
					    else if (interfaceName.indexOf('openURL') > -1) {
					        var url = evtData.params.url;
					        if (angular.isUndefined(url)) {
					            errorHandler(evt, '请提供需要打开的URL');
					            return;
					        }
					        window.openUrl(url);

					        result = {
					            'message': 'openUrl success'
					        };
					        successHandler(evt, {
					            'result': result
					        });
					    }
						/**
						 * 关闭应用
						 */
						else if (interfaceName.indexOf('closeApp') > -1) {
							var AppMarket = $injector.get('AppMarket');
							
							try {
								AppMarket.closeAppDetail();

								result = {
									'message': 'closeApp success'
								};
								successHandler(evt, {
									'result': result
								});
							} catch(e) {
								errorHandler(evt, 'closeApp error');
							}
						}
						/**
						 * 打开umeeting
						 */
						else if (interfaceName == 'joinUmeeting') {
							try {
								Meeting.joinUmeeting(evtData.params);
								successHandler(evt, {
									'result': {
										'message': 'join umeeting success'
									}
								});
							} catch(e) {
								errorHandler(evt, 'join umeeting error');
							}
						}
						/**
						 * 选择群成员
						 */
						else if (interfaceName.indexOf('selectDiscussionMember') > -1) {
							if ($rootScope.currentChat && $rootScope.currentChat.type == 'DISCUSSION') {
								let ChooseContact = $injector.get('ChooseContact');
								let Modal = $injector.get('Modal');
								evtData.params.selectDiscussionMember = true;
								ChooseContact.setOptions(evtData.params);
								Modal.open({
									templateUrl: 'templates/modal/custom_modal_body_temp.html',
									title: '选择群成员',
									className: 'modal-discussion',
									callback: function(selectedItems) {
										successHandler(evt, {
											'result': selectedItems
										});
									}
								})
								$rootScope.$apply();
								return;
							}
							errorHandler(evt, 'select discussion member error')
						} else if (interfaceName.indexOf('forward') > -1) {
							console.log(evtData.params);
							let Modal = $injector.get('Modal');
							Modal.open({
								templateUrl: 'templates/modal/custom_modal_body_temp.html',
								title: '转发给',
								className: 'modal-discussion',
								callback: function(selectedItems) {
									// successHandler(evt, {
									// 	'result': selectedItems
									// });
									console.log(`selectedItems:`, selectedItems);
									let message = Message.shareLinkChat($rootScope.urlTranslationResult.title, $rootScope.urlTranslationResult.cover_url, $rootScope.urlTranslationResult.summary, angular.element('#chatContent').val());
									$rootScope.hashSendMessages[message.delivery_id] = message;
									message.identifier = Message.getIdentifier(message);
									$scope.pushMessageToChat(message);
									$scope.sendMessage(message);
								}
							})
							$rootScope.$apply();
						}
						/**
						 * 转发
						 */
						else if (evtData.interface.indexOf('share') > -1) {
							let SessionList = $injector.get('SessionList');
							let Modal = $injector.get('Modal');
							let Notification = $injector.get('Notification');
							let Message = $injector.get('Message');
							const SHARE_SUCCESS_TIP = '分享成功!';

							let handleParams = function (settings) {
								let params = {
									max: 2,

								};
								angular.extend(params, settings.info);

								return params;
							};
							let packMessage = function (item, params) {
								let chat = $rootScope.messages[item.user_id];
								let msg = Message.shareChat(chat, params);

								return msg;
							};

							let params = handleParams(evtData.params);

							Modal.open({
								templateUrl: 'templates/modal/custom_modal_body_temp.html',
								title: '分享',
								className: 'modal-discussion',
								callback: function(selectedItems) {
									selectedItems.forEach(function (item, index) {
										// 组装会话
										SessionList.packageOfUser(item);
										// 组装消息
										let msg = packMessage(item, params);
										msg.identifier = Message.getIdentifier(msg);
										// 发送消息
										$rootScope.sendMessageToServer(Message.chatMsg(msg));
										// 消息处理
										Message.settingStatusSuccess(msg);
										$rootScope.storageMessage(msg);
										// 会话处理
										$rootScope.messages[item.user_id].push(msg);
										$rootScope.messages[item.user_id].lastActivityTime = msg.delivery_time;
										$rootScope.messages[item.user_id].lastMessage = msg.search_content;
										$rootScope.messages[item.user_id].lastMessageId = msg.delivery_id;
										Notification.showMessage(SHARE_SUCCESS_TIP, 'success');
									});

									if (selectedItems.length === 0) {
										successHandler(evt, {
											result: ''
										});
									}
								}
							})
							$rootScope.$apply();
						}
						/**
						 * 图片预览
						 */
						else if (evtData.interface.indexOf('imgPreview') > -1) {
							// TODO
						}
					});
				};

				return {
					getReInitTimesMax: getReInitTimesMax, 
					getReInitInterval: getReInitInterval, 
					successHandler: successHandler,
					errorHandler: errorHandler,
					postReady: postReadyFn, 
					sdkInit: sdkInit
				};
			}
		]);
})(angular);